"""
视频工具 Web API 主应用文件
整合各个功能模块的API蓝图
"""

from flask import Flask
from flask_cors import CORS
import os
import logging
import sys

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))

from config.config import config
from app.tools.utils import setup_logging

# 导入各个API蓝图
from app.api.audio_api import audio_bp
from app.api.subtitle_api import subtitle_bp
from app.api.image_api import image_bp
from app.api.video_api import video_bp
from app.api.system_api import system_bp
from app.api.file_upload import file_upload_bp
from app.api.merge_api import merge_bp

def create_app():
    """创建Flask应用实例"""
    # 创建Flask应用
    app = Flask(__name__)
    
    # 加载配置
    config_name = os.environ.get('FLASK_CONFIG', 'default')
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    
    # 设置CORS
    CORS(app)
    
    # 设置日志
    setup_logging(app.config['LOG_LEVEL'], app.config['LOG_FILE'])
    
    # 注册蓝图
    app.register_blueprint(audio_bp)
    app.register_blueprint(subtitle_bp)
    app.register_blueprint(image_bp)
    app.register_blueprint(video_bp)
    app.register_blueprint(system_bp)
    app.register_blueprint(file_upload_bp)
    app.register_blueprint(merge_bp)
    
    # 添加根路由
    @app.route('/', methods=['GET'])
    def index():
        """API根路径"""
        return {
            'message': '视频工具 Web API 服务',
            'version': '1.0.0',
            'endpoints': {
                'audio': {
                    'extract': '/audio/extract',
                    'merge': '/audio/merge',
                    'merge_with_timestamps': '/audio/merge_with_timestamps'
                },
                'upload': {
                    'audio': '/upload/audio',
                    'audio_batch': '/upload/audio/batch',
                    'audio_list': '/upload/audio/list'
                },
                'subtitle': {
                    'add': '/subtitle/add',
                    'format': '/subtitle/format'
                },
                'image': {
                    'remove_watermark': '/image/remove_watermark',
                    'create_gif': '/image/create_gif'
                },
                'video': {
                    'convert': '/video/convert',
                    'compress': '/video/compress',
                    'info': '/video/info',
                    'mask': '/video/mask',
                    'add_background_music': '/video/add_background_music',
                    'add_background_music_with_options': '/video/add_background_music_with_options',
                    'merge_audio': '/video/merge_audio'
                },
                'merge': {
                    'upload_file': '/merge/upload_file',
                    'apply_mask': '/merge/apply_mask',
                    'add_subtitle': '/merge/add_subtitle',
                    'merge_audio': '/merge/merge_audio',
                    'add_background_music': '/merge/add_background_music',
                    'download_final_video': '/merge/download_final_video',
                    'cleanup': '/merge/cleanup'
                },
                'system': {
                    'health': '/system/health',
                    'cleanup': '/system/cleanup'
                }
            },
            'pages': {
                'docs': '/docs',
                'video_mask_simple': '/video-mask-simple',
                'subtitle_simple': '/subtitle-simple',
                'add_background_music': '/add-background-music',
                'video_audio_merge': '/video-audio-merge'
            }
        }
    
    # 添加导航页面路由
    @app.route('/index', methods=['GET'])
    def index_page():
        """导航页面"""
        import os
        doc_path = os.path.join(os.path.dirname(__file__), '..', '..', 'doc', 'index.html')
        if os.path.exists(doc_path):
            with open(doc_path, 'r', encoding='utf-8') as f:
                return f.read()
        else:
            return {'error': '导航页面文件不存在'}, 404
    
    # 添加文档路由
    @app.route('/docs', methods=['GET'])
    def api_docs():
        """API文档页面"""
        import os
        doc_path = os.path.join(os.path.dirname(__file__), '..', '..', 'doc', 'api_docs.html')
        if os.path.exists(doc_path):
            with open(doc_path, 'r', encoding='utf-8') as f:
                return f.read()
        else:
            return {'error': 'API文档文件不存在'}, 404
    

    
    # 添加视频遮挡工具页面路由
    @app.route('/video-mask-simple', methods=['GET'])
    def video_mask_simple():
        """视频遮挡工具页面"""
        import os
        doc_path = os.path.join(os.path.dirname(__file__), '..', '..', 'doc', 'video_mask_simple.html')
        if os.path.exists(doc_path):
            with open(doc_path, 'r', encoding='utf-8') as f:
                return f.read()
        else:
            return "页面文件不存在", 404
    
    # 添加字幕设置工具页面路由
    @app.route('/subtitle-simple', methods=['GET'])
    def subtitle_simple():
        """字幕设置工具页面"""
        import os
        doc_path = os.path.join(os.path.dirname(__file__), '..', '..', 'doc', 'subtitle_simple.html')
        if os.path.exists(doc_path):
            with open(doc_path, 'r', encoding='utf-8') as f:
                return f.read()
        else:
            return "页面文件不存在", 404
    
    # 添加背景音乐工具页面路由
    @app.route('/add-background-music', methods=['GET'])
    def add_background_music():
        """背景音乐工具页面"""
        import os
        doc_path = os.path.join(os.path.dirname(__file__), '..', '..', 'doc', 'add_background_music_guide.html')
        if os.path.exists(doc_path):
            with open(doc_path, 'r', encoding='utf-8') as f:
                return f.read()
        else:
            return "页面文件不存在", 404
    
    # 添加视频音频合并工具页面路由
    @app.route('/video-audio-merge', methods=['GET'])
    def video_audio_merge():
        """视频音频合并工具页面"""
        import os
        doc_path = os.path.join(os.path.dirname(__file__), '..', '..', 'doc', 'video_audio_merge.html')
        if os.path.exists(doc_path):
            with open(doc_path, 'r', encoding='utf-8') as f:
                return f.read()
        else:
            return "页面文件不存在", 404
    
    # 添加静态文件服务路由
    @app.route('/static/<path:filename>')
    def static_files(filename):
        """静态文件服务"""
        import os
        static_path = os.path.join(os.path.dirname(__file__), '..', '..', 'doc', filename)
        if os.path.exists(static_path):
            from flask import send_file
            return send_file(static_path)
        else:
            return {'error': f'文件 {filename} 不存在'}, 404
    
    return app

# 创建应用实例
app = create_app()

if __name__ == '__main__':
    # 启动时清理旧文件
    from app.tools.utils import cleanup_old_files
    cleanup_old_files(app.config['UPLOAD_FOLDER'])
    cleanup_old_files(app.config['OUTPUT_FOLDER'])
    
    logging.info(f"视频工具服务启动在 {app.config['HOST']}:{app.config['PORT']}")
    app.run(debug=app.config['DEBUG'], host=app.config['HOST'], port=app.config['PORT']) 